<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2023-03-03 16:44:11
 * @LastEditors: wning wning.neu_sr
 * @LastEditTime: 2023-09-16 21:53:52
-->
<template>
  <div class="form-panel person">
    <div style="margin-bottom: 16px">
      <!-- <el-button type="primary" @click="handleSearch"> 查询 </el-button> -->
      <el-button type="primary" :icon="buttonIcons('add')" @click="addOrUpdateRow('')">
        {{ $t('common.add') }}</el-button
      >
    </div>

    <x-table
      ref="tableCom"
      :pagination="pagination"
      :data-source="tableData"
      :loading="loading"
      :row-key="'id'"
      @on-change="handleTableChange"
      @on-selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <!-- 可编辑列 -->
      <el-table-column prop="name" label="人员名称" min-width="120" :render-header="renderHeader"> </el-table-column>
      <el-table-column prop="certType" label="证件类型" min-width="120" :render-header="renderHeader">
        <div class="item" slot-scope="scope">
          <span>{{ selectDictLabel(dictOptions['certificate_type'], scope.row['certType']) }}</span>
        </div>
      </el-table-column>
      <el-table-column prop="certCode" label="证件号码" min-width="120" :render-header="renderHeader">
      </el-table-column>
      <el-table-column prop="certScan" label="证件扫描件" min-width="120" :render-header="renderHeader">
        <div class="item" slot-scope="scope">
          <el-button size="small" type="text" @click="handleDownload(scope.row.certScan)">{{
            scope.row.certScanName
          }}</el-button>
        </div>
      </el-table-column>
      <el-table-column prop="education" label="学历" min-width="120"></el-table-column>
      <el-table-column prop="educationScan" label="学历扫描件" min-width="120">
        <div class="item" slot-scope="scope">
          <el-button size="small" type="text" @click="handleDownload(scope.row.educationScan)">{{
            scope.row.educationScanName
          }}</el-button>
        </div>
      </el-table-column>
      <el-table-column prop="workExperience" label="工作经验" min-width="120">
        <div class="item" slot-scope="scope">
          <span>{{ scope.row.workExperience }}年</span>
        </div>
      </el-table-column>
      <el-table-column prop="quantity" label="职称信息" min-width="120">
        <div class="item" slot-scope="scope">
          <el-button size="small" type="text" @click="handePostName(scope.row.id, 'PersonnelTitleDialog')"
            >查看</el-button
          >
        </div>
      </el-table-column>
      <el-table-column prop="contractPeriod" label="劳务合同有效期至" min-width="170"> </el-table-column>
      <el-table-column prop="contractScan" label="劳务合同扫描件" min-width="120">
        <div class="item" slot-scope="scope">
          <el-button size="small" type="text" @click="handleDownload(scope.row.contractScan)">{{
            scope.row.contractScanName
          }}</el-button>
        </div>
      </el-table-column>
      <el-table-column prop="socialSecurity" label="社保证明扫描件" min-width="120">
        <div class="item" slot-scope="scope">
          <el-button size="small" type="text" @click="handleDownload(scope.row.socialSecurity)">{{
            scope.row.socialSecurityName
          }}</el-button>
        </div>
      </el-table-column>
      <el-table-column prop="socialSecurityDate" label="社保证明开具时间" min-width="170"> </el-table-column>
      <el-table-column prop="quantity" label="执业资格" min-width="120">
        <div class="item" slot-scope="scope">
          <el-button size="small" type="text" @click="handePostName(scope.row.id, 'CertificateDialog')">查看</el-button>
        </div>
      </el-table-column>
      <el-table-column prop="quantity" label="人员有效性" min-width="120">
        <div class="item" slot-scope="scope">
          <x-state-cell
            :stateClass="scope.row['state'] === 0 ? 'danger' : scope.row['state'] ? 'success' : ''"
            :text="selectDictLabel(dictOptions['system.preset'], scope.row['state'])"
          />
        </div>
      </el-table-column>

      <!--删除操作-->
      <el-table-column fixed="right" label="操作" width="120">
        <template slot-scope="scope">
          <el-link type="primary" style="margin-right: 8px" @click="addOrUpdateRow(scope.row.id)">编辑</el-link>
          <el-link type="danger" :underline="false" @click="delRow(scope.row.id)">删除</el-link>
        </template>
      </el-table-column>
    </x-table>

    <x-dialog
      title="人员基本信息"
      :show.sync="visible"
      v-if="visible"
      :before-close="handleClose"
      width="60%"
      @onCancel="handleClose"
      @onSubmit="handleSubmit"
    >
      <el-form
        :model="params"
        class="demo-form-inline"
        ref="params"
        :rules="rules"
        label-position="top"
        label-width="auto"
      >
        <el-row :gutter="36">
          <el-col :span="8">
            <el-form-item label="人员名称" prop="name">
              <el-input v-model="params.name" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="证件类型" prop="certType">
              <x-select v-model="params.certType" :options="dictOptions['certificate_type']" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="证件号码" prop="certCode">
              <el-input v-model="params.certCode" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="学历" prop="education">
              <el-input v-model="params.education" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工作经验" prop="workExperience">
              <el-input v-model="params.workExperience" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="劳务合同有效期至" prop="contractPeriod">
              <el-date-picker
                v-model="params.contractPeriod"
                value-format="yyyy-MM-dd"
                size="mini"
                placeholder="请选择"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="社保证明开具时间" prop="socialSecurityDate">
              <el-date-picker
                v-model="params.socialSecurityDate"
                value-format="yyyy-MM-dd"
                size="mini"
                placeholder="请选择"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="人员有效性" prop="state">
              <x-radio-group :list-data="dictOptions['system.state']" v-model="params.state"></x-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="证件扫描件" prop="certScanFile">
              <!-- 执照上传 -->
              <x-upload
                ref="certScanFileUpload"
                tips=""
                :edit-flag="true"
                :limit="1"
                :fileSize="20"
                :old-file-list="params.certScanFile || []"
                :file-type="['jpg', 'jpeg', 'png']"
                @uploadChange="uploadChange"
              >
              </x-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="学历扫描件" prop="educationScanFile">
              <!-- 执照上传 -->
              <x-upload
                ref="educationFileUpload"
                tips=""
                :edit-flag="true"
                :limit="1"
                :fileSize="20"
                :old-file-list="params.educationScanFile || []"
                :file-type="['jpg', 'jpeg', 'png']"
              >
              </x-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="劳务合同扫描件" prop="contractScanFile">
              <!-- 执照上传 -->
              <x-upload
                ref="contractScanFileUpload"
                tips=""
                :edit-flag="true"
                :limit="1"
                :fileSize="20"
                :old-file-list="params.contractScanFile || []"
                :file-type="['jpg', 'jpeg', 'png']"
                @uploadChange="uploadChange"
              >
              </x-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="社保证明扫描件" prop="socialSecurityFile">
              <!-- 执照上传 -->
              <x-upload
                ref="socialSecurityFileUpload"
                tips=""
                :edit-flag="true"
                :limit="1"
                :fileSize="20"
                :old-file-list="params.socialSecurityFile || []"
                :file-type="['jpg', 'jpeg', 'png']"
              >
              </x-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </x-dialog>
    <PersonnelTitleDialog ref="PersonnelTitleDialog"></PersonnelTitleDialog>
    <CertificateDialog ref="CertificateDialog"></CertificateDialog>
  </div>
</template>
<script>
  import {
    selectDictLabel,
    TableListMixin,
    QueryDictMixin,
    buttonIcons,
    checkNumber,
    cloneDeep,
    throttle,
    omit
  } from '@package/utils'

  import {
    apiPostStaffPageApi as listUrl,
    apiPostStaffAdd,
    apiPutStaffUpdate,
    apiDeleteStaffDelete,
    apiGetStaffFindById
  } from '../api'
  import { EnumApiCode } from '../../../../../../globalEnum.js'
  import PersonnelTitleDialog from './personnelTitleDialog.vue'
  import CertificateDialog from './certificateDialog.vue'

  export default {
    name: 'PersonForm',
    components: {
      PersonnelTitleDialog,
      CertificateDialog
    },
    mixins: [TableListMixin, QueryDictMixin],
    props: {
      supplierId: {
        type: String
      }
    },
    data() {
      return {
        listUrl,
        otherParam: {
          supplierId: this.supplierId
        },
        dictKeys: ['certificate_type', 'system.preset', 'system.state'],
        visible: false,
        editId: '',
        params: {
          name: '',
          certCode: '',
          certType: '',
          certScanFile: [],
          certScan: '',
          certScanName: '',
          education: '',
          educationScanFile: [],
          educationScan: '',
          educationScanName: '',
          contractScanFile: [],
          contractScan: '',
          contractScanName: '',
          socialSecurityFile: [],
          socialSecurity: '',
          socialSecurityName: '',
          state: 1
        },
        buttonIcons,
        rules: {
          name: [{ required: true, message: '请输入人员名称', trigger: ['change'] }],
          certType: [{ required: true, message: '请选择证件类型', trigger: ['change'] }],
          certCode: [{ required: true, message: '请输入证件号码', trigger: ['change'] }],
          certScanFile: [{ required: true, message: '请上传证件扫描件', trigger: ['change'] }]
        },
        multipleSelection: []
      }
    },
    watch: {
      supplierId: {
        handler(val) {
          if (val) {
            // this.getDetail()
          }
        },
        immediate: true,
        deep: true
      }
    },
    methods: {
      selectDictLabel,
      handleDownload(url) {
        window.open(url)
      },
      handleSearch(val) {
        this.queryParam = { ...val, supplierId: this.supplierId }
        this.loadData()
      },
      handleClose() {
        this.$refs.params.resetFields()
        this.params = {}
        console.log('222', this.params)
        this.visible = false
      },
      uploadChange() {
        this.params.certScanFile = this.$refs.certScanFileUpload.fileList.map((item) => {
          return {
            fileName: item.name || item.fileName,
            filePath: item.filePath || item.response.data.filePath,
            fileType: (item.name || item.fileName).slice((item.name || item.fileName).lastIndexOf('.') + 1),
            remark: item.remark
          }
        })
        if (this.params.certScanFile?.length > 0) {
          const item = this.params.certScanFile[0] || {}
          this.params.certScan = item.filePath
          this.params.certScanName = item.fileName
        }
      },
      handleSubmit: throttle(function () {
        this.$refs.params.validate(async (valid) => {
          if (valid) {
            const educationFile = this.$refs.educationFileUpload.fileList[0] || {}
            const contractFile = this.$refs.contractScanFileUpload.fileList[0] || {}
            const socialSecurityFile = this.$refs.socialSecurityFileUpload.fileList[0] || {}
            const param = {
              ...this.params,
              supplierId: this.supplierId,
              contractPeriod: `${this.params.contractPeriod} 23:59:59`,
              socialSecurityDate: `${this.params.socialSecurityDate} 23:59:59`,
              educationScan: educationFile.name || educationFile.fileName,
              educationScanName: educationFile.filePath || educationFile.response?.data?.filePath,
              contractScan: contractFile.name || contractFile.fileName,
              contractScanName: contractFile.filePath || contractFile.response?.data?.filePath,
              socialSecurity: socialSecurityFile.name || socialSecurityFile.fileName,
              socialSecurityName: socialSecurityFile.filePath || socialSecurityFile.response?.data?.filePath
            }
            const { code, msg } = param.id ? await apiPutStaffUpdate(param) : await apiPostStaffAdd(param)
            if (code === EnumApiCode.Success) {
              param.id
                ? this.$message.success(this.$t('common.editSuccess'))
                : this.$message.success(this.$t('common.newSuccess'))
              this.$emit('handleSuccess')
              this.handleClose()
              this.loadData()
            } else {
              this.$message.error(msg)
            }
          } else {
            return false
          }
        })
      }, 1000),
      // 点击职称信息列
      handePostName(id, name) {
        if (name) {
          this.$refs[name].show(id)
        }
      },
      renderHeader(h, { column }) {
        return [h('span', { style: 'color:#F56C6C;padding-right:4px' }, '*'), h('span', ` ${column.label}`)]
      },
      addOrUpdateRow(id = '') {
        this.editId = id
        if (id) {
          this.getDetail(id)
        } else {
          this.visible = true
        }
      },
      getDetail(id) {
        apiGetStaffFindById(id).then((res) => {
          const {
            certScan,
            certScanName,
            educationScan,
            educationScanName,
            contractScan,
            contractScanName,
            socialSecurity,
            socialSecurityName,
            state
          } = cloneDeep(res.data)
          const certScanFile = certScan ? [{ fileName: certScanName, filePath: certScan }] : []
          const educationScanFile = educationScan ? [{ fileName: educationScanName, filePath: educationScan }] : []
          const contractScanFile = contractScan ? [{ fileName: contractScanName, filePath: contractScan }] : []
          const socialSecurityFile = socialSecurity ? [{ fileName: socialSecurityName, filePath: socialSecurity }] : []
          this.params = {
            ...res.data,
            certScanFile,
            educationScanFile,
            contractScanFile,
            socialSecurityFile,
            state: String(state)
          }
          console.log('33', this.params)
          this.visible = true
        })
      },
      delRow(id) {
        this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: this.$t('common.sure'),
          cancelButtonText: this.$t('common.cancel')
        })
          .then(() => {
            this.handleDelete(id)
          })
          .catch(() => {})
      },
      /**
       * 删除接口
       *
       */
      handleDelete(id) {
        apiDeleteStaffDelete(id).then((res) => {
          if (res.code === EnumApiCode.Success) {
            this.$message.success(this.$t('common.deleteSuccess'))
          } else {
            this.$message.error(res.msg)
          }
          this.loadData()
        })
      },

      // 批量删除
      handleBatchDel() {
        if (this.multipleSelection.length === 0) {
          this.$message.error('请至少选择一条数据')
          return
        }
        this.delRow()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      tableRowClassName(row) {
        // 设置row对象的index
        row.row.lineNumber = row.rowIndex + 1
      },
      handleVaildForm() {
        return new Promise((resolve) => {
          this.$refs.params.validate((valid) => {
            resolve(valid)
          })
        })
      },
      onSumit() {
        return new Promise((resolve, reject) => {
          if (this.tableData.length > 0) {
            resolve()
          } else {
            reject('人员信息数据不能为空!')
          }
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .person {
    padding: 10px;
  }
</style>
